package com.itstudy.study.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itstudy.study.response.R;
import com.itstudy.study.student.entity.Student;
import com.itstudy.study.student.mapper.StudentMapper;
import com.itstudy.study.student.pojo.request.StudentRequest;
import com.itstudy.study.student.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenxiaofan
 */

@Service
public class StudentImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {


    @Override
    public Student getStudentByCode(StudentRequest request) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getCode, request.getCode());
        Student student = this.baseMapper.selectOne(wrapper);
        return student;
    }

    @Override
    public List<Student> list(StudentRequest request) {
        List<Student> list = this.list();
        return list;
    }

    @Override
    public Page<Student> page(StudentRequest request) {
        Page<Student> page = this.page(new Page<>((long) request.getPageSize(), (long) request.getPageNo()));
        return page;
    }

    @Override
    public R add(StudentRequest request) {
        List<Student> list = this.list(request);
        List<String> codeList = list.stream().map(Student::getCode).collect(Collectors.toList());
        if (codeList.contains(request.getCode())) {
            return new R("1001", "编码已存在");
        }
        Student student = new Student();
        BeanUtils.copyProperties(request, student);
        this.save(student);
        return new R("200", "保存成功");
    }
}
